import 'dart:developer';
import 'dart:io';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'state.dart';

class ChatVideoPlayerLogic extends GetxController {
  final ChatVideoPlayerState state = ChatVideoPlayerState();
  late EMVideoMessageBody body;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    if (Get.arguments != null) {
      state.message = Get.arguments['message'];
      body = state.message.body as EMVideoMessageBody;
      checkFile();
    }
    // 添加下载监听
    addMessageEvent();
  }
  /// 检查资源是否存在
  checkFile() async {
    final file = File(body.localPath);
    if (await file.exists()) {
      state.player.setDataSource(body.localPath, autoPlay: true);
    } else {
      EasyLoading.showToast('视频下载中,请稍后');
     await EMClient.getInstance.chatManager.downloadAttachment(state.message);
    }
  }

  /// 播放视频
  payVideo() async {
    EasyLoading.dismiss();
    Future.delayed(const Duration(seconds: 1),() async {
      final file = File(body.localPath);
      if (await file.exists()) {
        state.player.setDataSource(body.localPath, autoPlay: true);
      } else {
        EasyLoading.showToast('视频异常');
      }
    });
  }
  // eventBus() {
  //   EventBus.instance.addListener('open_video', (arg) async {
  //     if (arg == state.message.msgId) {
  //       payVideo();
  //     }
  //   });
  // }
  /// 触发下载进度
  addMessageEvent(){
    EMClient.getInstance.chatManager.addMessageEvent(
     state.tag,
      ChatMessageEvent(
        onSuccess: (msgId, msg) {
          log('视频下载完毕');
          EasyLoading.dismiss();
          state.message = msg;
          body = msg.body as EMVideoMessageBody;
          payVideo();
        },
        // 收到回调之后，可以将发送的消息状态进行更新，或者进行其他操作。
        onError: (msgId, msg, error) {
          EasyLoading.showToast('视频下载失败');
          Get.back();
        },
        // 对于附件类型的消息，如图片，语音，文件，视频类型，上传或下载文件时会收到相应的进度值，表示附件的上传或者下载进度。
        onProgress: (msgId, progress) {
          log('视频下载进度===:$progress%');
        },
      ),
    );
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    EMClient.getInstance.chatManager.removeMessageEvent(state.tag);
    state.player.release();
  }
}
